package com.app.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.app.service.IMessageService;
import com.app.util.AppSecurityUtil;

@Controller
public class MessageController {
	@Autowired
	private IMessageService messageService;
	String message;

	@RequestMapping(value = "/getMessage", method = RequestMethod.GET)
	public ModelAndView getMessage(HttpServletRequest request, ModelMap map) {
		if (AppSecurityUtil.isAnonymousUser()) {
			return new ModelAndView("redirect:login");
		}
		Map<Integer, String> messageMap = messageService.getMessageList();
		if (messageMap.size() == 0) {
			map.addAttribute("info_msg", "No Messages were found.");
		} else {
			map.addAttribute("msgList", messageMap);
		}
		return new ModelAndView("success");
	}

	@RequestMapping(value = "/deleteMessage", method = RequestMethod.GET)
	public ModelAndView deleteMessage(HttpServletRequest request, ModelMap map) {
		if (AppSecurityUtil.isAnonymousUser()) {
			return new ModelAndView("redirect:login");
		}
		messageService.deleteMessage(Integer.parseInt(request
				.getParameter("key")));
		return new ModelAndView("redirect:getMessage");
	}

	@RequestMapping(value = "/postMessage", method = RequestMethod.GET)
	public ModelAndView postMessag(ModelMap model, HttpServletRequest request) {
		if (AppSecurityUtil.isAnonymousUser()) {
			return new ModelAndView("redirect:login");
		}
		messageService.postMessage(message);
		model.addAttribute("suc_msg", "Message Successfully Posted.");
		return new ModelAndView("success");
	}

	@RequestMapping(value = "/postMessage", method = RequestMethod.POST)
	public ModelAndView postMessage(ModelMap model, HttpServletRequest request) {
		if (AppSecurityUtil.isAnonymousUser()) {
			return new ModelAndView("redirect:login");
		}
		message = request.getParameter("msgBox");
		return new ModelAndView("redirect:postMessage");
	}

}
